package com.github.xzb617.client.flow.core.statics;

import java.util.Objects;
import java.util.concurrent.atomic.LongAdder;

/**
 * 时间窗的样本时间切片窗口
 * <p>
 *   假设一个时间窗为 1s, 样本时间窗为 500ms
 *   那么时间窗就会切割成2个样本时间窗，如下示例：
 *   时间窗：| ———— 1s ————  | ———— 2s ————  | ———— 3s ————  |
 *   样本窗：|-500ms-|-500ms-|-500ms-|-500ms-|-500ms-|-500ms-|
 * <p/>
 */
public class Slice {

    /**
     * 总访问量的计数器
     */
    private LongAdder totalCounter;

    /**
     * 成功通过的计数器
     */
    private LongAdder passCounter;

    /**
     * 切片开始时间
     */
    private long startTime;

    /**
     * 切片窗口时间
     */
    private long sliceInterval;

    public Slice(long startTime, long sliceInterval) {
        this.totalCounter = new LongAdder();
        this.passCounter = new LongAdder();
        this.startTime = startTime;
        this.sliceInterval = sliceInterval;
    }

    public LongAdder getTotalCounter() {
        return totalCounter;
    }

    public LongAdder getPassCounter() {
        return passCounter;
    }

    public long getStartTime() {
        return startTime;
    }

    public long getSliceInterval() {
        return sliceInterval;
    }

    public void addTotalCount(int count) {
        this.totalCounter.add(count);
    }

    public void addPassCount(int count) {
        this.passCounter.add(count);
    }


    public Slice reset(long startTime) {
        this.totalCounter.reset();
        this.passCounter.reset();
        this.startTime = startTime;
        return this;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Slice that = (Slice) o;
        return startTime == that.startTime &&
                sliceInterval == that.sliceInterval;
    }

    @Override
    public int hashCode() {
        return Objects.hash(startTime, sliceInterval);
    }

}
